package com.wangshili.sys.service.Impl;

import java.util.HashSet;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.wangshili.pojo.sys.entity.SysUser;
import com.wangshili.sys.dao.SysMenuDao;
import com.wangshili.sys.dao.SysRoleDao;
import com.wangshili.sys.dao.SysRoleMenuDao;
import com.wangshili.sys.dao.SysUserDao;
import com.wangshili.sys.dao.SysUserRoleDao;
import com.wangshili.sys.vo.SysUserDept;

@Service
public class ShiroRealm extends AuthorizingRealm{

	@Autowired
	SysUserDao sysUserDao;
	@Autowired
	SysUserRoleDao sysUserRoleDao;
	@Autowired
	SysMenuDao sysMenuDao;
	@Autowired
	SysRoleMenuDao sysRoleMenuDao;
	/**
	 * 授权器
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行授权");
		SysUser user = (SysUser)principals.getPrimaryPrincipal();//获取登录的对象
		
		//根据用户id找出对应的角色id
		List<Integer> roleIds = sysUserRoleDao.selectObjectByUserId(user.getId());

		Integer[] arr = new Integer[]{};
		//没有权限异常
		if(roleIds==null || roleIds.size()<1)
			throw new AuthorizationException();
		//根据角色id找出对应的门店id
		List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByRoleIds(roleIds.toArray(arr));
		//找出对应的权限
		List<String> listPermission = 
				sysMenuDao.listPermissionByIds(menuIds.toArray(arr));

		//没有权限异常
		if(listPermission==null || listPermission.size()<1)
			throw new AuthorizationException();//没有权限异常
		
		HashSet<String> hashSet = new HashSet<String>();
		
		for(String per:listPermission) { //存入set集合
			if(!StringUtils.isEmpty(per))//判空，因为有的权限是空 的
				hashSet.add(per);
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(hashSet);//将set集合放入授权器中
		return info;
	}

	
    /**
     * 设置凭证匹配器(要与用户添加操作使用相同的加密算法)
     */
    @Override
    public void setCredentialsMatcher(
        CredentialsMatcher credentialsMatcher) {
            //构建凭证匹配对象
            HashedCredentialsMatcher cMatcher=
            new HashedCredentialsMatcher();
            //设置加密算法
            cMatcher.setHashAlgorithmName("MD5");
            //设置加密次数
            cMatcher.setHashIterations(1);
            super.setCredentialsMatcher(cMatcher);
    }
	/**
	 * 认证用户名和密码
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行认证");
		/**转换*/
		UsernamePasswordToken tokenU = (UsernamePasswordToken)token;
		String username = tokenU.getUsername();//找出输入的用户名
		SysUser user = sysUserDao.selectUserByUserName(username);//找出对应的用户信息
		if(user==null)
			throw new UnknownAccountException();//抛出没有用户异常
		if(user.getValid()!=1)
			throw new LockedAccountException();//用户禁用异常
		
		ByteSource bytes = ByteSource.Util.bytes(user.getSalt());//转换盐值字符串成ByteSource类型
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
				user,
				user.getPassword(),
				bytes,
				getName()
				);
		return info;
	}
	
}
